package org.ptkparty.client.activity;

import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;

import org.ptkparty.client.ClientFactory;
import org.ptkparty.client.model.PlaceProxy;
import org.ptkparty.client.request.PlaceRequest;
import org.ptkparty.client.view.place.PlaceView;
import org.ptkparty.client.view.place.PlacesView;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.adapters.ListEditor;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.gwt.client.RequestFactoryEditorDriver;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class PlacesActivity implements Activity {

	private static Driver driver = GWT.create(Driver.class);

	interface Driver extends RequestFactoryEditorDriver<List<PlaceProxy>, ListEditor<PlaceProxy, PlaceView>> {
	}

	private ClientFactory clientFactory;
	private PlaceRequest placeRequest;
	private PlacesView view;

	public PlacesActivity(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		view = clientFactory.getPlacesView();
		view.setPresenter(this);
		panel.setWidget(view);

		clientFactory.getFactory().placeRequest().getAll().fire(new Receiver<List<PlaceProxy>>() {

			@Override
			public void onSuccess(final List<PlaceProxy> response) {
				placeRequest = clientFactory.getFactory().placeRequest();

				driver.initialize(clientFactory.getEventBus(), clientFactory.getFactory(), view.asEditor());

				driver.edit(response, placeRequest);

				view.initProvider();

				view.selectFirstPlace();

				placeRequest.save(view.asEditor().getList()).to(new Receiver<Void>() {

					@Override
					public void onConstraintViolation(Set<ConstraintViolation<?>> violations) {
						driver.setConstraintViolations(violations);
					}

					@Override
					public void onSuccess(Void response) {

					}

				});
			}
		});
	}

	@Override
	public String mayStop() {
		return null;
	}

	@Override
	public void onCancel() {
	}

	@Override
	public void onStop() {
	}

	public PlaceProxy addPlace() {
		final PlaceProxy newPlace = placeRequest.create(PlaceProxy.class);
		newPlace.setName("Nouveau boulodrome");
		return newPlace;
	}

	public void delete(final PlaceProxy selectedProxy) {
		if (selectedProxy != null) {
			clientFactory.getFactory().placeRequest().remove().using(selectedProxy).fire(new Receiver<Void>() {

				@Override
				public void onSuccess(Void response) {
					view.removePlaceEditor(selectedProxy);
				}

			});
		}
	}

	public void save() {
		driver.flush().fire();
	}

}